package com.jjty.dataGenerator.bg.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.jjty.dataGenerator.bg.entity.BgAccount;
import com.jjty.dataGenerator.bg.service.IBgAccountService;
import com.jjty.dataGenerator.common.RedisKey;
import com.jjty.dataGenerator.exception.ServiceException;
import com.jjty.dataGenerator.utils.JWTUtils;
import com.jjty.dataGenerator.utils.PasswordDecoder;
import com.jjty.dataGenerator.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @Author: huangyulong
 * @createTime: 2023-08-28 10:42
 * @Description:
 */
@Service
public class LoginService {

    @Autowired
    IBgAccountService bgAccountService;

    public String login(String username, String password) {
        password = PasswordDecoder.decode(password);
        BgAccount bgAccount = bgAccountService.getByAccount(username,DigestUtil.sha256Hex(password));
        if(bgAccount == null){
            throw new ServiceException("账号或密码错误");
        }

        String token = null;
        //创建token
        try {
            Map<String,String> claims = new HashMap();
            claims.put("id",""+bgAccount.getId());
            claims.put("username",bgAccount.getUsername());
            claims.put("nickname",bgAccount.getNickname());
            token = JWTUtils.createToken(claims);

            RedisUtils.stringRedis.opsForValue().set(RedisKey.LOGIN+bgAccount.getId(),token,12,TimeUnit.HOURS);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException("登录异常，请联系系统管理员");
        }
        return token;
    }

}
